package com.Product;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.enclose.dataBasePool;
import com.model.AllCater.AllCatergoriesInfo;
import com.model.AllCater.AllCatergoriesInfoSon;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

//查询商品所有类别
@WebServlet("/Product/AllCategories")
public class AllCategories extends HttpServlet {
    @Override

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<AllCatergoriesInfoSon> list = new ArrayList<>();
        try {
            //重数据库中找数据
            dataBasePool dataBasePool = new dataBasePool();
            Statement statement = dataBasePool.getStatement();
            String sql = "SELECT category_id,category_name FROM category";
            ResultSet resultSet = statement.executeQuery(sql);

            while (resultSet.next()){
                list.add(new AllCatergoriesInfoSon(resultSet.getInt("category_id"),resultSet.getString("category_name") ));
            }

            dataBasePool.close(statement,resultSet);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {


        }
        AllCatergoriesInfo allCatergoriesInfo = new AllCatergoriesInfo();
        allCatergoriesInfo.setCode(200);
        allCatergoriesInfo.setMsg("success!");
        allCatergoriesInfo.setData(list);

        //putout
        ObjectMapper objectMapper = new ObjectMapper();
        String str = objectMapper.writeValueAsString(allCatergoriesInfo);
        resp.getWriter().write(str);
    }
}
